import React, { Component } from "react";

import { Table, Input, InputNumber, Popconfirm, Form, Button,DatePicker,Row,Col, Modal } from "antd";
import Content from "../../components/Content/Content";

import moment from "moment";

const { Item } = Form;
const data = [];
for (let i = 0; i < 30; i++) {
  data.push({
    key: i.toString(),
    name: `Edrward ${i}`,
    age: 32,
    address: `London Park no. ${i}`
  });
}
const EditableContext = React.createContext();

class EditableCell extends React.Component {
  getInput = () => {
    if (this.props.inputType === "number") {
      return <InputNumber />;
    }
    return <Input />;
  };

  renderCell = ({ getFieldDecorator }) => {
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item style={{ margin: 0 ,width:'200%'}}>
            {getFieldDecorator(dataIndex, {
              rules: [
                {
                  required: true,
                  message: `Please Input ${title}!`
                }
              ],
              initialValue: record[dataIndex]
            })(this.getInput())}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  render() {
    return (
      <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
    );
  }
}

class EditableTable extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      dataSource: data, 
      editingKey: "" ,

      selectedRowKeys: [],

      searchParams: {},
      
      count: 0,
      pageNum: 1,
      pageSize: 100
    };
    this.columns = [
      {
        title: "序号",
        dataIndex: "id",
        editable: false,
      },
      {
        title: "出库批次",
        dataIndex: "compound_ckpc",
        editable: true
      },
      {
        title: "化合物数量",
        dataIndex: "compound_hhwsl",
        editable: true
      },
      {
        title: "取样时间",
        dataIndex: "delivery_time",
        editable: true
      },
      {
        title: "筛选模型",
        dataIndex: "m_id",
        editable: true
      },
      {
        title: "取样人",
        dataIndex: "user_share",
        editable: true
      },
      {
        title: "所属单位",
        dataIndex: "unit_name	",
        editable: true
      },
      {
        title: "是否反馈",
        dataIndex: "is_feedback",
        editable: true
      },
      {
        title: "反馈结果",
        dataIndex: "sevice_result",
        editable: true
      },
      {
        title: "反馈时间",
        dataIndex: "feedback_time",
        editable: true
      },
      {
        title: "操作",
        dataIndex: "operation",
        fixed: 'right',
        width: 200,
        render: (text, record) => {
          const { editingKey } = this.state;
          const editable = this.isEditing(record);
          return editable ? (
            <span>
              <EditableContext.Consumer>
                {form => (
                  <Button
                  type='primary'
                    onClick={() => this.save(form, record.id)}
                    style={{ marginRight: 8 }}
                  >
                    保存
                  </Button>
                )}
              </EditableContext.Consumer>
              <Popconfirm
                title="确认取消?"
                onConfirm={() => this.cancel(record.id)}
              >
                <Button>取消</Button>
              </Popconfirm>
            </span>
          ) : (
            <Button
            type='dashed'
              disabled={editingKey !== ""}
              onClick={() => this.edit(record.id)}
            >
              编辑
            </Button>
          );
        }
      }
    ];
  }

  isEditing = record => record.id === this.state.editingKey;

  cancel = () => {
    this.setState({ editingKey: "" });
  };

  save(form, id) {
    form.validateFields((error, row) => {
      if (error) {
        return;
      }

      const url = global.api.compoundFeedback;
      return global.network.post(url, row)
      .then(res => {  

        const newData = [...this.state.dataSource];
        const index = newData.findIndex(item => id === item.id);
        if (index > -1) {
          const item = newData[index];
          newData.splice(index, 1, {
            ...item,
            ...row
          });
          this.setState({ data: newData, editingKey: "" });
        } else {
          newData.push(row);
          this.setState({ data: newData, editingKey: "" });
        }

        Modal.success({
          content: '保存成功!',
        });
      })
      .catch(err => {
        Modal.error({
          content: '保存出错!',
        });
      })  

    });
  }

  edit(id) {
    this.setState({ editingKey: id });
  }
  onSelectChange = selectedRowKeys => {
    console.log("selectedRowKeys changed: ", selectedRowKeys);
    this.setState({ selectedRowKeys });
  };


  // 导出
  doOut = () => {
    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false,
      });
    }, 1000);
  };

  loadData = (current = 1) => {
    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false
      });
    }, 1000);
    
    const url = global.api.compoundFeedback
    + '?compound_ckpc=' + (this.state.searchParams.compound_ckpc || "")
    + '&compound_hhwsl=' + (this.state.searchParams.compound_hhwsl || "")
    + '&m_id=' + (this.state.searchParams.m_id || "")
    + '&delivery_time=' + (this.state.searchParams.delivery_time || "")
    + '&worker=' + (this.state.searchParams.worker || "")
    + '&unit_name=' + (this.state.searchParams.unit_name || "")
    + '&sevice_result=' + (this.state.searchParams.sevice_result || "")
    + '&feedback_time=' + (this.state.searchParams.feedback_time || "")
    + '&is_feedback=' + (this.state.searchParams.is_feedback || "");
    return global.getdata.get(url, {page_index: current, page_size: this.state.pageSize, search: {}})
    .then(res => {
      this.setState({dataSource: res.results, count: res.count})
    })
    .catch(err => {
      Modal.error({
        content: '网络异常!',
      });
    }) 

  }

  componentDidMount() {
    this.loadData(1);
  }

  onSelectChange = selectedRowKeys => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
    console.log(selectedRowKeys.length);
  };

  render() {
    const components = {
      body: {
        cell: EditableCell
      }
    };

    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: col.dataIndex === "age" ? "number" : "text",
          dataIndex: col.dataIndex,
          title: col.title,
          editing: this.isEditing(record)
        })
      };
    });

    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 9 }
      }
    };
    const { loading, selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };

    const hasSelected = selectedRowKeys.length > 0;

    return (
      <Content>
         <Form
          {...formItemLayout}
          onSubmit={this.onSubmit}
          colon={false}
          style={{ borderBottom: "20px solid #f0f2f5" }}
        >
          <div style={{ display: "flex" }}>
            <span style={{ flex: 1 }}>
              <Item label="出库批次">
                <Input onChange={e => this.state.searchParams.compound_ckpc = e.target.value} />
              </Item>
              <Item label="化合物数量">
                <Input onChange={e => this.state.searchParams.compound_hhwsl = e.target.value} />
              </Item>
              <Item label="筛选模型">
                <Input onChange={e => this.state.searchParams.m_id = e.target.value} />
              </Item>
              <Item label="取样时间">
                <DatePicker onChange={(date, dateStr) => this.state.searchParams.delivery_time = dateStr} style={{ width: "100%" }} />{" "}
              </Item>
              <Item label="取样人">
                <Input onChange={e => this.state.searchParams.worker = e.target.value} />
              </Item>
            </span>
            <span style={{ flex: 1 }}>
              <Item label="所属单位">
                <Input onChange={e => this.state.searchParams.unit_name = e.target.value} />
              </Item>
              <Item label="是否反馈">
                <Input onChange={e => this.state.searchParams.is_feedback = e.target.value} />
              </Item>
              <Item label="反馈结果">
                <Input onChange={e => this.state.searchParams.sevice_result = e.target.value} />
              </Item>
              <Item label="反馈时间">
                <DatePicker onChange={(date, dateStr) => this.state.searchParams.feedback_time = dateStr} style={{ width: "100%" }} />{" "}
              </Item>
            </span>
          </div>

          <Item wrapperCol={{ span: 10, offset: 3 }}>
            <Row guuter={16}>
              <Col span={5}>
              <Button type="primary" loading={this.state.loading} onClick={()=>this.loadData(1)}>
                  查询
                </Button>
              </Col>
             
            </Row>
          </Item>
        </Form>
        <Button type="primary" onClick={this.doOut} disabled={!hasSelected} loading={loading} style={{ marginLeft: 20,marginTop: 15}}>
            导出
          </Button>
        <EditableContext.Provider value={this.props.form}>
          <Table
            rowSelection={rowSelection}
            components={components}
            bordered
            dataSource={this.state.dataSource}
            columns={columns}
            rowClassName="editable-row"
            pagination={{
              onChange: this.cancel
            }}
            // scroll={{ x: 3000 }}
            scroll={{ x: 2500, y: 300 }}
          />
        </EditableContext.Provider>
      </Content>
    );
  }
}

const CompoundFeedback = Form.create()(EditableTable);
export default CompoundFeedback;
